﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Portal.Logic.Creators;
using Portal.Logic.Services;
using Portal.Model;

namespace Portal.Logic.Providers
{
	/// <summary>
	/// Class <see cref="UserProvider"/> define user provider
	/// </summary>
	public class UserProvider : IUserProvider
	{
		#region Fields
		private readonly IUserService _service;
		private readonly IUserCreator _cretor;
		#endregion

		#region .ctor
		/// <summary>
		/// Class <see cref="UserProvider"/> constructor
		/// </summary>
		/// <param name="service"></param>
		public UserProvider(IUserService service, IUserCreator cretor)
		{
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (cretor == null)
			{
				throw new ArgumentNullException("creator");
			}
			_cretor = cretor;
			_service = service;
		}
		#endregion

		#region Methods

		/// <summary>
		/// Gets user by identity
		/// </summary>
		/// <param name="logon">Logon</param>
		/// <returns>
		/// User
		/// </returns>
		public IUser GetUser(string logon)
		{
			if (string.IsNullOrWhiteSpace(logon))
			{
				return null;
			}

			var user = _service.GetBy(logon);
			if (user == null)
			{
				user = _cretor.From(logon);
				user = _service.AddOrUpdate(user);
			}
			return user;

		}

		#endregion
	}
}
